import React from 'react'
import './AddAD.css'
import { Input, Button, Select, DatePicker, Space, Upload, Modal, Radio,message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment';
import axios from '../../../utils/http'
import { ADDADVERT,ADDADPHOTOS } from '../../../utils/api'
const { RangePicker } = DatePicker;

const { Option } = Select;






class AddAD extends React.Component {
    constructor() {
        super()
        this.state = {
            // 图片上传
            previewVisible: false,
            previewImage: '',
            previewTitle: '',
            // 上传文件
            fileList: [
            ],
            // 单选框
            data: {
                
            }

        };
    }


    //  广告位置下拉款
    onChange = (value) => {
        let add = {...this.state.data}
        console.log(add);
        console.log(value);
        add.advertAdd = value
        this.setState({
            data:add
        })
    }

    // 是否开启单选框
    onChangeRadio = (value) => {
        let add = { ...this.state.data }
        // console.log(value);
        add.advertStatu = value.target.value
        this.setState({
            data:{...add}
        })
        // this.setState={
        //     data:{
        //         advert_statu:value.target.value
        //     }
        // }
        // console.log(value.target.value);
    }
    // 广告名称
    onchangeInput=(e)=> {
        // let obj = this.state
        // obj.data.advert_name = e.target.value
        // this.setState(obj)
        let add={ ...this.state.data }
        // console.log(value);
        add.advertName = e.target.value
        this.setState({
            data:{...add}
        })

    }
    // 广告链接
    onchangeInputLink = (value) => {
        let add = { ...this.state.data }
        console.log( value.target.value);
        add.link = value.target.value
        this.setState({
            data:{...add}
        })
    }


    //   时间选择器
    onChangeTime = (dates, dateStrings) => {
        // console.log('From: ', dates[0], ', to: ', dates[1]);
        // console.log('From: ', dateStrings[0], ', to: ', dateStrings[1]);
        // console.log(dateStrings[0]);
        let add = { ...this.state.data }
        // console.log(value);
        add.advertStart = dateStrings[0]
        add.advertLast = dateStrings[1]
        this.setState({
            data:{...add}
        })
    }
    //广告图片
    // 这个就是生成预览
    getBase64 = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }
      

    handleCancel = () => this.setState({ previewVisible: false });


    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await this.getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };

    handleChange = ({ fileList }) => this.setState({ fileList });


    buttonAdd = async () => {
        console.log(this.state.fileList);
        let formData=new FormData()
        for (let index = 0; index < this.state.fileList.length; index++) {
            formData.append('file',this.state.fileList[index].originFileObj)
        }
        // formData.append('file',this.state.fileList[0].originFileObj)
        await axios({
            url:ADDADPHOTOS,
            method:'post',
            data:formData
        }).then(data=>{
            console.log(data);
            let obj = {...this.state.data}
            obj.advertUrl=data.data.data[0]
            this.setState({
                data:{...obj}
            })
        })       
            await axios({
                url: ADDADVERT,
                method: 'post',
                data: this.state.data
            }).then((data) => {
                console.log(data);
                if (data.data.code===200) {
                    message.success('添加成功', 3);
                    this.props.history.push("/Home/wangZhan/AdvertisingList/AdvertisingListTabel");
                }else{
                    message.error('添加失败',3);
                }
            })
        
        // console.log(data1);

        

        // console.log(this.state.data);
        
    }











    render() {
        //  广告图片
        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );









        return (
            <div className='AddAD'>
                {/* 我是添加广告 */}
                <div className='adName'>
                    <span>广告名称：</span>
                    <span><Input placeholder="请输入广告名称" onChange={this.onchangeInput} /></span>
                </div>
                <div>
                    <span>广告位置：</span>
                    <span><Select
                        showSearch
                        style={{ width: 200 }}
                        placeholder="请选择广告位置"
                        optionFilterProp="children"
                        onChange={this.onChange}
                        filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                        <Option value="首页轮播广告位">首页轮播广告位</Option>
                        <Option value="热榜顶部广告位">热榜顶部广告位</Option>
                        <Option value="积分商城顶部广告位">积分商城顶部广告位</Option>
                    </Select>,</span>
                </div>
                {/* <div>
                    <span>开始日期：</span>
                    <span>
                        <Input placeholder="请输入广告名称" />
                    </span>
                </div> */}
                <div>
                    <span>日期选择：</span>
                    <Space direction="vertical" size={12}>
                        <RangePicker
                            ranges={{
                                Today: [moment(), moment()],
                                'This Month': [moment().startOf('month'), moment().endOf('month')],
                            }}
                            onChange={this.onChangeTime}
                        />
                    </Space>
                </div>
                <div>
                    <span>广告链接：</span>
                    <span><Input placeholder="请输入广告链接" onChange={this.onchangeInputLink} /></span>
                </div>
                <div>
                    <span>广告图片：</span>
                    <Upload
                        action=''
                        beforeUpload={()=>{return false}}
                        listType="picture-card"
                        fileList={fileList}
                        onPreview={this.handlePreview}
                        onChange={this.handleChange}
                    >
                        {fileList.length >= 8 ? null : uploadButton}
                    </Upload>
                    <Modal
                        visible={previewVisible}
                        title={previewTitle}
                        footer={null}
                        onCancel={this.handleCancel}
                    >
                        <img alt="example" style={{ width: '100%' }} src={previewImage} />
                    </Modal>
                </div>
                <div>
                    <span>是否开启：</span>
                    <Radio.Group name="radiogroup" defaultValue={1} onChange={this.onChangeRadio}>
                        <Radio value={1}>开启</Radio>
                        <Radio value={0}>关闭</Radio>
                    </Radio.Group>


                </div>
                <div>
                    <Button type="primary" onClick={this.buttonAdd}>确定</Button>
                </div>


            </div>
        )
    }

}

export default AddAD